package com.bestcem.xm.survey.controller;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.componet.filestorage.service.StorageService;
import com.bestcem.xm.survey.entity.SurveyRespondentData;
import com.bestcem.xm.survey.grpc.client.QdesGrpcClient;
import com.bestcem.xm.survey.service.SurveyCommonService;
import com.bestcem.xm.survey.service.SurveyReportService;
import com.bestcem.xm.survey.service.SurveyRespondentDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;
import java.util.Optional;

import static com.bestcem.xm.survey.grpc.v1.services.RespondentSource.RESPONDENT_SOURCE_PREVIEW_VALUE;

@Slf4j
@Api(tags = "报告")
@RestController
@RequiredArgsConstructor
@RequestMapping("/survey/")
public class SurveyReportController {
    private @NonNull SurveyReportService surveyReportService;

    private @NonNull QdesGrpcClient qdesGrpcClient;
    private @NonNull SurveyCommonService surveyCommonService;
    private @NonNull SurveyRespondentDataService surveyRespondentDataService;
    private @NonNull StorageService storageService;

    @AuthIgnore
    @ApiOperation(value = "获取报告")
    @PostMapping(value = {"/report/{projectId:[a-fA-F0-9]{24}}"})
    public XmResultJson<JSONObject> report(@PathVariable(value = "projectId") String projectId,
                                           @RequestParam(value = "source") Integer source,
                                           @RequestBody JSONObject param) {
        return XmResultJson.success(surveyReportService.getReport(projectId, source, param));
    }

    @AuthIgnore
    @ApiOperation(value = "评分报告上传")
    @PostMapping(value = {"/report/upload/{project_id:[a-fA-F0-9]{24}}/"})
    public XmResultJson<?> reportUpload(@PathVariable(value = "project_id") String projectId,
                                        @RequestParam("file") MultipartFile file,
                                        @RequestParam("seq") Integer seq,
                                        @RequestParam("source") Integer source,
                                        @RequestParam(value = "c_type", defaultValue = "pc") String c_type,
                                        @RequestParam(value = "allParams") String allParamsStr) {
        Assert.notNull(file, "报告文件pdf必须有");
        Assert.notNull(file.getOriginalFilename(), "报告文件pdf必须有");
        if (!file.getOriginalFilename().endsWith("pdf")) {
            return XmResultJson.fail(-1, "文件类型只支持pdf");
        }

        Assert.notNull(qdesGrpcClient.getProject(projectId), String.format("project [project_id=%s] not found", projectId));

        JSONObject all_params = new JSONObject();
        if (Objects.equals(RESPONDENT_SOURCE_PREVIEW_VALUE, source)) {
            all_params.put("source", source);
        } else {
            all_params = Optional.ofNullable(JSONObject.parseObject(allParamsStr)).orElse(new JSONObject());
            surveyCommonService.checkDeliverParams(all_params);
        }

        SurveyRespondentData rspd_data = surveyRespondentDataService.getOne(new LambdaQueryWrapper<SurveyRespondentData>()
                .eq(SurveyRespondentData::getSeq, seq)
                .eq(SurveyRespondentData::getProjectId, projectId)
                .last("limit 1"));
        Assert.notNull(rspd_data, String.format("Respondent_data[project_id=%s,seq=%s] not found", projectId, seq));

        String fileName = String.format("%s_%s.pdf", seq, c_type);
        String url = storageService.upload(file, fileName, "survey/report/", new Dict()).getUrl();

        JSONObject report_url = new JSONObject();
        String key = String.format("%s_pdf_url", c_type);
        report_url.put(key, url);

        surveyRespondentDataService.update(null, new LambdaUpdateWrapper<SurveyRespondentData>()
                .eq(SurveyRespondentData::getId, rspd_data.getId())
                .set(SurveyRespondentData::getReportUrl, report_url.toJSONString()));
        JSONObject ret = new JSONObject();
        JSONArray ary = new JSONArray();
        ary.add(url);
        ret.put("urls", ary);
        return XmResultJson.success(ret);
    }
}